<?php

include_once(dirname(dirname(dirname(dirname(__FILE__)))) . '/engine/start.php');

include_once(dirname(dirname(__FILE__)) . '/_init.php');

$user = get_user_by_username('greengar');
login($user);

function port_user($link) {

    $mapping = array();
    $wp_users = 'Gr33ngAr_Us3R_users';
    $fields = '*';
    $query = "SELECT $fields FROM $wp_users";
    echo '<br>' . $query;
    $result = mysql_query($query, $link);
    while ($row = mysql_fetch_assoc($result)) {
        echo '<br>' . $row['user_email'];
        $wpid = $row['ID'];
        if($wpid <= 0) {
            echo '<br> wpid error';
            continue;
        }
        $username = $row['user_login'];
        $email = $row['user_email'];
        $name = $row['display_name'];
        $password = $row['user_pass'];
        echo '<br> I am ' . $username . ' with email: ' . $email;
        $userEntity = get_user_by_username($username);
        if ($userEntity) {
            echo '<br>' . $username . ' already exists';
            continue;
        }
        // WHAT TO DO??? THIS SHOULD NOT HAPPEN
        $userEntity = get_user_by_email($email);
        if ($userEntity && is_array($userEntity)) {
            $userEntity = array_shift($userEntity);
            if ($userEntity) {
                echo '<br>' . $email . ' already exists';
                continue;
            }
        }
        // WHAT TO DO??? THIS SHOULD NOT HAPPEN
        $lastname = $name;
        // DONT SEND EMAIL TO THESE OLD USER;
        $try = greengar_register($email, $username, $password, $firstname, $lastname, FALSE);

        if ($try) {
            $status = $try['status'];
            $message = $try['result'];
            if ($status == 200) {
                // Successfully create user, verify that
                echo '<br>' . $email . ' is created successfully';
                $userid = $message;
                $userEntity = get_entity($userid);
                if ($userEntity) {
                    // Set password for this one
                    $userEntity->password = mysql_real_escape_string($password);

                    $userEntity->setMetaData('isWPUser', 1);
                    $userEntity->clearMetaData(WHITEBOARD);
                    $userEntity->setMetadata(WHITEBOARD, 1);
                    //$userEntity->save();
                    $userEntity->save();
                    $mapping[$wpid] = $userid;
                    //$userEntity = get_entity($userid);
                    echo '<br> in database password is ' . $userEntity->password;
                    echo '<br> change ' . $userid . ' s passowrd to ' . $password;
                } else {
                    // Fail to set password for this one
                    echo '<br> failed to change ' . $userid . ' s passowrd to ' . $password;
                }
            } else {
                // What to do ???
                echo '<br>' . $email . ' is failed to create : ' . $message;
            }
        } else {
            echo '<br>' . $email . ' is failed to create : unexpected error happened';
        }
    }
    mysql_free_result($result);
    echo '<br> done port_user()';
    return $mapping;
}

function port_whiteboard($link) {
    //port_xmpp_account($link);
    port_whiteboard_friend($link);
}

function port_xmpp_account($link) {

    $map = array();

    $xmpp_account = 'ggs_wb_xmpp';
    $fields = '*';
    $query = "SELECT $fields FROM $xmpp_account";
    echo '<br>' . $query;
    $result = mysql_query($query, $link);
    while ($row = mysql_fetch_assoc($result)) {
        $wp_id = $row['user_id'];
        $username = $row['user_login'];
        $login = $row['xmpp_account'];
        $domain = $row['xmpp_domain'];

        echo '<br>' . $username . ' try ' . $login . '@' . $domain;

        // Fetch current domain
        $wp_usermeta = 'Gr33ngAr_Us3R_usermeta';
        $query = "SELECT $fields FROM $wp_usermeta WHERE user_id = $wp_id";
        $meta = mysql_query($query, $link);
        while ($current = mysql_fetch_assoc($meta)) {
            $meta_key = $current['meta_key'];
            $meta_value = $current['meta_value'];
            if ($meta_key == 'wb_xmpp_user') {
                $current_login = $meta_value;
            } else if ($meta_key == 'wb_xmpp_domain') {
                $current_domain = $meta_value;
            }
        }



        echo "<br> currently using $current_login@$current_domain";

        // Strip bad characters
        $blacklist2 = '\'/\\"*& ?#%^(){}[]~?<>;|¬`@-+=';
        for ($n = 0; $n < strlen($blacklist2); $n++) {
            $pos = strpos($username, $blacklist2[$n]);
            if ($pos != false) {
                $username = str_replace($blacklist2[$n], '_', $username);
            }
        }

        $userEntity = get_user_by_username($username);
        if ($userEntity) {
            login($userEntity);
            $userid = $userEntity->getGUID();
            if ($domain == $current_domain) {
                $map[$userEntity->username] = array(
                    'login' => $current_login,
                    'domain' => $current_domain
                );
                continue;
            }
            $account = greengar_whiteboard_add_xmppAccount($login, $domain, $userid);
            if ($account) {
                echo '<br> add ' . $account->owner_guid . ' s ' . json_encode($account->toArray());
            } else {
                echo '<br> failed to add  ' . $login . '@' . $domain;
            }
        }
    }

    foreach ($map as $username => $xmpp) {
        $userEntity = get_user_by_username($username);
        $login = $xmpp['login'];
        $domain = $xmpp['domain'];
        if ($userEntity) {
            login($userEntity);
            $userid = $userEntity->getGUID();

            $account = greengar_whiteboard_add_xmppAccount($login, $domain, $userid);
            if ($account) {
                echo '<br> add ' . $account->owner_guid . ' s ' . json_encode($account->toArray());
            } else {
                echo '<br> failed to add  ' . $login . '@' . $domain;
            }
        }
    }


    mysql_free_result($result);
}

function port_whiteboard_friend($link) {
    $offset = get_input('start');
    $limit = get_input('count');
    $whiteboard_friend = 'ggs_wb_friend';
    $fields = '*';
    $query = "SELECT $fields FROM $whiteboard_friend LIMIT $offset, $limit";
    echo '<br>' . $query;
    $result = mysql_query($query, $link);
    while ($row = mysql_fetch_assoc($result)) {
        $user_login = $row['user_login'];
        $friend_login = $row['friend_login'];
        // Strip bad characters
        $blacklist2 = '\'/\\"*& ?#%^(){}[]~?<>;|¬`@-+=';
        for ($n = 0; $n < strlen($blacklist2); $n++) {
            $pos = strpos($user_login, $blacklist2[$n]);
            if ($pos != false) {
                $user_login = str_replace($blacklist2[$n], '_', $user_login);
            }
        }

        // Strip bad characters
        $blacklist2 = '\'/\\"*& ?#%^(){}[]~?<>;|¬`@-+=';
        for ($n = 0; $n < strlen($blacklist2); $n++) {
            $pos = strpos($friend_login, $blacklist2[$n]);
            if ($pos != false) {
                $friend_login = str_replace($blacklist2[$n], '_', $friend_login);
            }
        }

        $userEntity = get_user_by_username($user_login);
        $friendEntity = get_user_by_username($friend_login);
        if ($userEntity && $friendEntity) {
            $userid = $userEntity->getGUID();
            $friendid = $friendEntity->getGUID();
            login($userEntity);
            $add = greengar_add_relationship($userid, $friendid, WHITEBOARD);
            if ($add) {
                echo '<br> add ' . $friendid . ' as friend of ' . $userid;
            } else {
                echo '<br> failed to add  ' . $friendid . ' - ' . $userid;
            }
        }
    }
    mysql_free_result($result);
}

function port_wp() {
    $dbhost = 'mysql50-84.wc2.dfw1.stabletransit.com';
    //$dbhost = '72.3.204.165';
    $dbname = '549152_wpuser';
    $dbuser = '549152_wpu';
    $dbpass = 'EvmD9EBfLj5k6hs9aqzC';
    $link = mysql_connect($dbhost, $dbuser, $dbpass);
    if (!$link) {
        die('link failed : ' . mysql_errno() . ', ' . mysql_error());
    }
    if (!mysql_select_db($dbname, $link)) {
        die('select_db failed : ' . mysql_errno() . ', ' . mysql_error());
    }

    //$mapping = port_user($link);
    port_whiteboard($link);

    mysql_close($link);
    
    //match_wb_drawings($mapping);
}

function match_artists($link, $mapping) {
    $query = sprintf("SELECT * FROM artists");
    $result = mysql_query($query, $link);
    while($row = mysql_fetch_assoc($result)) {
        $wpid = $row['userid'];
        $userid = $mapping[$wpid];
        $id = $row['id'];
        $role = $row['role'];
        $update = sprintf(
                "INSERT INTO elgg_artists (drawingid, userid, role) VALUES('%s', '%s', '%s')",
                $userid,
                $id,
                $role
                );
        mysql_query($update, $link);
        echo "<br> update $id 's user from $wpid to $userid";
    }
    
}

function match_wb_drawings($mapping) {
    $dbhost = 'mysql50-85.wc2.dfw1.stabletransit.com';
    //$dbhost = '72.3.204.165';
    $dbname = '549152_whiteboardg';
    $dbuser = '549152_whiteboar';
    $dbpass = 'ZGY6AWWGheBEZRpsZDsk';
    $link = mysql_connect($dbhost, $dbuser, $dbpass);
    if (!$link) {
        die('link failed : ' . 1 . ', ' . mysql_error());
    }
    if (!mysql_select_db($dbname, $link)) {
        die('select_db failed : ' . mysql_errno() . ', ' . mysql_error());
    }

    //$query = "";
    match_artists($link, $mapping);

    mysql_close($link);
}

port_wp();

//match_wb_drawings();
?>
